import requestSecurityService from "./requestSecurityService";
import router from "@/uni_modules/uniapp-kantboot/libs/router";
import crypto from "@/uni_modules/uniapp-kantboot/libs/crypto";
import request from "@/uni_modules/uniapp-kantboot/libs/request";
import requestService from "@/uni_modules/uniapp-kantboot/libs/request/requestService";
import storage from "@/uni_modules/uniapp-kantboot/libs/storage";
import config from "@/uni_modules/uniapp-kantboot/libs/config";

/**
 * 安全发送（即加密发送）
 */
let send = async (obj) => {
    // 检查参数
    obj = requestSecurityService.check(obj);

    // 获取服务器的公钥
    await requestSecurityService.requestServerPublicKey();


    let newObj = {
        uri: "/security/request/simpleForward/" + obj.uri,
        data: {
            content: requestSecurityService.encryptData(obj)
        },
        header: {
            ...obj.header,
        }
    }


    request.send({
        isReconnect: obj.isReconnect,
        isJumpLogin: obj.isJumpLogin,
        uri: newObj.uri,
        data: newObj.data,
        header: {
            ...obj.header,
        },
        stateSuccess: (res) => {
            console.log("====");
            console.log("========")

            // AES解密data.data
            let decryptData = crypto.decryptData(res.data, requestSecurityService.getClientKey());
            let json = JSON.parse(decryptData);

            if (json.success) {
                requestService.toStateSuccess(json, obj);
                return;
            }
            // 如果有res.status则是服务器错误
            if (json.status) {
                let statusCodeToStateFail = requestService.statusCodeToStateFail(json.status, obj);
                requestService.toStateFail(statusCodeToStateFail, obj);
                return;
            }

            requestService.toStateFail(json, obj);
        },
        stateFail: (res) => {
            console.log("stateFail", res);
            // 如果安全保障过期，则重新请求安全保障
            if (res.stateCode === "securityExpire") {
                console.log("安全保障过期，重新请求安全保障");
                // 清空客户端密钥和服务端公钥
                requestSecurityService.clearKey();
                request.send(obj);
                return;
            }

            // 如果服务端公钥错误，则重新请求服务端公钥
            if (res.stateCode === "publicKeyError") {
                console.log("服务端公钥错误，重新请求服务端公钥");
                // 清空客户端和服务端公钥
                requestSecurityService.clearKey();
                // 重新请求服务端公钥
                request.send(obj);
                return;
            }

            if (res.stateCode === "securityRisk") {
                console.error("安全风险，请求终止");
                // 清空客户端密钥和服务端公钥
                requestSecurityService.clearKey();
                // 清除token
                storage.remove(config.keyConfig.token);
                uni.showToast({
                    title: "存在信息安全风险",
                    icon: "none"
                });
                // 判断页面
                let currentPages = getCurrentPages();
                if (currentPages.length > 0) {
                    let currentPage = currentPages[currentPages.length - 1];
                    console.log(currentPage.route,"currentPage.route");
                    if (currentPage.route === "pages/into/into") {
                        // 重新请求服务端公钥
                        request.send(obj);
                        return;
                    }
                }

                setTimeout(() => {
                    // 进入安全风险页面
                    router.reLaunch("/pages/into/into");
                }, 1000);

                return;
            }
            obj.stateFail(res);
        }
    })
}

let clearKey = () => {
    requestSecurityService.clearKey();
}

export default {
    send,
    clearKey
}

